// pages/calendar/calendar.js
let app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        dateArr: [],
        week: ['日', '一', '二', '三', '四', '五', '六'],
        info: [],
        validityLowerBound: '1970-01-01',
        validityUpperBound: '2030-01-01',
        initDayObj: ''
    },
    navD(e){
        const day = e.currentTarget.dataset.day;
        
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];
        prevPage.setData({
          initDayObj: day
        })
        wx.navigateBack({})
        // wx.navigateTo({
        //     url: `/pages/calendarList/calendarList?day=${JSON.stringify(day)}&info=${JSON.stringify(this.data.info)}`
        // })
    },  
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const date = new Date();
        const curYear = date.getFullYear();
        const curMonth = date.getMonth() + 1;
        wx.setNavigationBarTitle({
          title: `${curYear}-${curMonth}`,
        })
        // this.load(curYear, curMonth, 'init')
        console.log(options)
        this.setData({
          initDayObj: JSON.parse(options.initDayObj)
        })

        app.globalData.post({
            url: '/activity/getList',
            data: {
                validityLowerBound: this.data.validityLowerBound,
                validityUpperBound: this.data.validityUpperBound
            },
            success: (data) => {
                this.setData({
                    info: data.data
                })
                
                this.load(curYear, curMonth, 'init')
            }
        })
    },
    judge(obj, info){
        let activityArr = []
        info.afterConsume.forEach(val => {
            let valWeekDay = val.date == 7 ? 0 : val.date
            let valYear = val.validityLowerBound.split('-')[0]
            let valYear1 = val.validityUpperBound.split('-')[0]
            let valMonth = val.validityLowerBound.split('-')[1]
            let valMonth1 = val.validityUpperBound.split('-')[1]
            let valDay = val.validityLowerBound.split('-')[2]
            let valDay1 = val.validityUpperBound.split('-')[2]
            if (!+valMonth[0]) {
                valMonth = valMonth.substr(1)
                valMonth1 = valMonth1.substr(1)
            }
            if (!+valDay[0]) {
                valDay = valDay.substr(1)
                valDay1 = valDay1.substr(1)
            }
            // console.log(valYear, valYear1, valMonth, valMonth1, valDay, valDay1)
            if (+obj.year >= +valYear && +obj.year <= +valYear1) {
                if (+obj.month == +valMonth) {
                  if (+obj.day >= +valDay && +obj.weekDay == valWeekDay) {
                        activityArr.push(val)
                    }
                }
                if (+obj.month > +valMonth && +obj.month < +valMonth1 && +obj.weekDay == valWeekDay) {

                    activityArr.push(val)
                }
                if (+obj.month == +valMonth1) {
                  if (+obj.day <= valDay1 && +obj.weekDay == valWeekDay) {
                        activityArr.push(val)
                    }
                }
            }
        })
        info.deliverDirectly.forEach(val => {
            let valYear = val.deliverDate.split('-')[0]
            let valMonth = val.deliverDate.split('-')[1]
            let valDay = val.deliverDate.split('-')[2]
            if (!+valMonth[0]) {
                valMonth = valMonth.substr(1)
            }
            if (!+valDay[0]) {
                valDay = valDay.substr(1)
            }
            if (+valYear == +obj.year && +valMonth == +obj.month && +valDay == +obj.day){
                activityArr.push(val)
            }
        })
        return activityArr
    },
    load(year, month, type) {
        let dateArr = this.data.dateArr
        let i, max
        let monthNum = 4
        if (type === 'prev') {
            i = -monthNum
            max = 0
        }
        else if (type === 'init') {
            i = 0
            max = monthNum
        }
        else if (type === 'next') {
            i = 1
            max = monthNum + 1
        }
        for (; i < max; i++) {
            let obj = {}
            if (month + i < 1) {
                obj.year = year - 1
                obj.month = month + i + 12
            }
            else if (month + i > 12) {
                obj.year = year + 1
                obj.month = month + i - 12
            }
            else {
                obj.year = year
                obj.month = month + i
            }
            obj.firstDayOfWeek = this.getFirstDayOfWeek(obj.year, obj.month);
            obj.days = [];
            const thisMonthDays = this.getThisMonthDays(obj.year, obj.month);
            for (let i = 1; i <= thisMonthDays; i++) {
              let weekDay = this.getWeekDays(obj.year, obj.month - 1, i)
              let judgeObj = this.judge({ ...obj, day: i, weekDay}, this.data.info)
                
                obj.days.push({
                    activityArr: judgeObj,
                    year: obj.year,
                    month: obj.month,
                    day: i,
                    hasActivity: !!judgeObj.length,
                    weekDay
                });
            }
            if (type === 'prev') {
                // let copy = this.data.dateArr.slice()
                dateArr.splice(i + monthNum, 0, obj)
                // this.setData({
                //     dateArr
                // }, () => {
                //   setHeight()
                // })
            }
            else if (type === 'init' || type === 'next') {
                dateArr = [...dateArr, obj]
                // this.setData({
                //     dateArr: [...this.data.dateArr, obj]
                // }, () => {
                //   setHeight()
                // })
            }
        }
        this.setData({
          dateArr
        }, () => {
          setHeight(this.data.dateArr, (dateArr) => {
            this.setData({
              dateArr
            })
          })
        })
        
        function setHeight(dateArr, cal){
          wx.createSelectorQuery().selectAll('.calender-wrap').boundingClientRect((rects) => {         
            rects.forEach((rect, index) => {
              //傻逼小程序下拉刷新top算不准，直接拿height计算
              dateArr[index].top = index ? (dateArr[index - 1].top + rect.height + 30) : 0
            })
            cal(dateArr)
          }).exec()
        }
        
        // console.log(wx.createSelectorQuery().selectAll('.calender-wrap'))
    },
    onPullDownRefresh() {
        console.log('下拉刷新')
        let year = this.data.dateArr[0].year
        let month = this.data.dateArr[0].month
        this.load(year, month, 'prev')
        wx.setNavigationBarTitle({
          title: `${this.data.dateArr[0].year}-${this.data.dateArr[0].month}`,
        })
        wx.stopPullDownRefresh()
    },
    onReachBottom() {
        console.log('触底')
        let year = this.data.dateArr[this.data.dateArr.length - 1].year
        let month = this.data.dateArr[this.data.dateArr.length - 1].month
        this.load(year, month, 'next')
    },
    getThisMonthDays(year, month) {
        return new Date(year, month, 0).getDate();
    },
    getWeekDays(year, month, day) {
        return new Date(year, month, day).getDay();
    },
    getFirstDayOfWeek(year, month) {
        return new Date(Date.UTC(year, month - 1, 1)).getDay();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onPageScroll(e){
      let top = e.scrollTop
      let dateArr = this.data.dateArr 
      dateArr.forEach((val, index) => {
        if (index && top >= dateArr[index - 1].top && top <= val.top ){
          // console.log(dateArr[index - 1])
          wx.setNavigationBarTitle({
            title: `${dateArr[index - 1].year}-${dateArr[index - 1].month}`,
          })
        }
      })
    },
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];
      prevPage.setData({
        initDayObj: this.data.initDayObj
      })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})